module Main where

import qualified LexAn as LA
import qualified SynAn as SA
import qualified Lan_1 as L1
import qualified Lan_2 as L2
import Optimiz

import System.Environment (getArgs)
import Data.List.Split

firstFSM = LA.FSM
  { LA.symbols = L1.symbols_1
  , LA.start_state = L1.s_q
  , LA.eos = L1.eos
  , LA.delta = L1.delta_1
  }
secondFSM = SA.FSM
  { SA.start_state = L2.start_state
  , SA.eos = L2.eos
  , SA.empty_el = L2.empty_el
  , SA.empty_stack = L2.empty_stack
  , SA.halt = L2.halt
  , SA.delta = L2.delta
  }

--test = "Y = (X + 14) * 1.12e-10"
test = "COST = (PRICE + TAX) * 0.98"
test1 = LA.execFSM firstFSM test
test2 = fst $ SA.execFSM secondFSM test1
test3 = optimiz test2 
test4 = optimiz test3 

print_text :: [String] -> String
print_text x = 
  concat $ map (flip (++) "\n") x

main :: IO()
main = do
  args <- getArgs
{-
  let file_name = 
    if (null args)
    then "input.txt"
    else args !! 0
-}
  let file_name = args !! 0
  raw_text <- readFile file_name
  let text = head $ splitOn "\n" raw_text
  
  let res1 = LA.execFSM firstFSM text
  let res2 = fst $ SA.execFSM secondFSM res1
  let res3 = optimiz res2 
  let res4 = optimiz res3 

  putStrLn "Raw string:"
  putStrLn text
  putStrLn ""

  putStrLn "Lexeme chain:"
  putStrLn $ show res1
  putStrLn ""

  putStrLn "Raw object code:"
  putStr $ print_text res2
  putStrLn ""
  
  putStrLn "Optimized object code:"
  putStr $ print_text res4
  putStrLn ""


